package com.mapler.autoresponder.service;

import com.mapler.model.AdModel;
import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.service.INotifier;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import com.mapler.utility.Util;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author none
 */
public class AutoResponderClick implements Runnable {

    private SModel sModel;
    private ArrayList<UAModel> uaModels;
    ArrayList<AdModel> addModels;
    private Random random;
    private static Logger log = Logger.getLogger(AutoResponderClick.class);
    private INotifier iNotifier;

    public AutoResponderClick(INotifier iNotifier, SModel sModel, ArrayList<UAModel> uaModels, ArrayList<AdModel> addModels) {
        this.sModel = sModel;
        this.uaModels = uaModels;
        this.addModels = addModels;
        this.iNotifier = iNotifier;
    }

    public AutoResponderClick(SModel iModel) {
        this.sModel = iModel;
    }

    public Random getRandom() {
        if (random == null) {
            random = new Random();
        }
        return random;
    }

    public void setRandom(Random random) {
        this.random = random;
    }

    @Override
    public void run() {
        try {
            this.doPost();
        } catch (Throwable ex) {
            iNotifier.notify("Post:Run:: stopped for error: " + ex.getMessage());
            log.debug("Post:Run:: stopped causes " + ex);
        }
    }

    private EmailModel getSendMailModel(UAModel uam) {
        EmailModel emr = new EmailModel();
        emr.setSmtphost(uam.getServer());
        emr.setSmtpport(uam.getPort());
        emr.setUsername(uam.getUsername());
        emr.setPassword(uam.getUsername());
        emr.setSsl(uam.getSsl());
        
        return  emr;
    }

    private void doPost() {
        try {
            if (sModel.getChangeIP().equals("1")) {
                if (sModel.getProxy().isEmpty() || sModel.getName().isEmpty() || sModel.getPass().isEmpty()) {
                    iNotifier.notify("Responder:: proxy, username or password is empty. Going to try for another account");
                    log.debug("Responder:goVPN:: proxy, username or password is empty. Going to try for another account");
                    return;
                }
            }
            int serverCount = 1;
            int mailCount = 0;
            boolean firstServer = true;
            UAModel emailServerModel = uaModels.get(0);
            IMAPAutoResponder responder = new IMAPAutoResponder(iNotifier, getSendMailModel(emailServerModel));

            ArrayList<MimeMessage> unReadEmails = this.readMail();
            int postIPlimit = Integer.parseInt(sModel.getPostPerIP());

            for (MimeMessage mimeMessage : unReadEmails) {
                if (sModel.isStopEngine()) {
                    break;
                }
                mailCount = mailCount + 1;
                if (mailCount > sModel.getPostPerAccout()) {
                    uaModels.remove(0);
                    this.updateRunAccount(emailServerModel);
                    emailServerModel = uaModels.get(0);
                    EmailModel em  = this.getSendMailModel(emailServerModel);
                    responder.setEmailModel(em);
                    
                    serverCount = serverCount + 1;
                    mailCount = 0;
                }

                if (sModel.getChangeIP().equals("1")) {
                    if (serverCount > postIPlimit) {
                        iNotifier.notify("Responder:: Going to disconnect VPN.");
                        Util.disConnect(sModel.getProxy(), sModel.getName(), sModel.getPass());
                    }

                    if (firstServer || serverCount > postIPlimit) {
                        iNotifier.notify("Responder:: Going to connect VPN.");
                        boolean connect = Util.connect(sModel.getProxy(), sModel.getName(), sModel.getPass());
                        if (!connect) {
                            iNotifier.notify("Responder:: unable to connect VPN.");
                            log.debug("Responder:goVPN:: unable to connect for " + sModel.getProxy());
                            break;
                        }
                        firstServer = false;
                    }
                }
                
                AdModel adModel;
                if(sModel.isRandom()){
                    int index = this.getRandom().nextInt(addModels.size() - 1);
                    adModel = this.addModels.get(index);
                    this.addModels.remove(index);
                } else {
                    adModel = this.addModels.get(0);
                } 
                this.addModels.remove(0);
                responder.manualReply(mimeMessage, adModel);
                this.updatePostInfo(adModel);
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    private ArrayList<MimeMessage> readMail() {
        EmailModel em = new EmailModel();
        em.setServer("");
        em.setUsername("shahinur.bd@gmail.com");
        em.setPassword("cre@@7te");
        IMAPAutoReader reader = new IMAPAutoReader(iNotifier, em);
        return reader.read();
    }

    private void updateRunAccount(UAModel emailSModel) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(sModel.getUsername()).append("</username>");
            request.append("<password>").append(sModel.getPassword()).append("</password>");
            request.append("<id>").append(emailSModel.getId()).append("</id>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=netellerAccount/updateWorking";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            log.debug("updateWorking:: update " + msg);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    private void updatePostInfo(AdModel adModel) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(sModel.getUsername()).append("</username>");
            request.append("<password>").append(sModel.getPassword()).append("</password>");
            request.append("<id>").append(adModel.getId()).append("</id>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=netellerAccount/updateWorking";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            log.debug("updateWorking:: update " + msg);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    
    public static void main(String s[]) {
        try {
            AutoResponderClick click = new AutoResponderClick(null);
            INotifier iNotifier = new INotifier() {
                @Override
                public void notify(String info) {
                }

                @Override
                public void write(String info) {

                }
            };
            EmailModel em = new EmailModel();
            em.setServer("");
            em.setUsername("skyroproject10@gmail.com");
            em.setPassword("ab142536");         
            em.setSmtphost("smtp.gmail.com");
            em.setSmtpport("587");
            em.setAuto(true);
            // em.setSmtpport("465");
            IMAPAutoReader reader = new IMAPAutoReader(iNotifier, em);
            
            
            EmailModel emr = new EmailModel();
            emr.setServer("");
            emr.setUsername("shahinur.bd@gmail.com");
            emr.setPassword("cre@@7te");
            emr.setSmtphost("smtp.gmail.com");
            emr.setSmtpport("587");
            IMAPAutoResponder responder = new IMAPAutoResponder(iNotifier, emr);
            /*if(!emr.getSmtphost().isEmpty()){
             responder.reply(null);
             return;
             }*/

            System.getProperties();

            ArrayList<MimeMessage> msgs = reader.read();
            MimeMessage mm = null;
            for (MimeMessage m : msgs) {
                mm = m;
                responder.reply(m);
                break;

            }
            //System.out.println("......................."+mm.getContent()+mm.isMimeType("text/plain"));
        } catch (Throwable ex) {
            java.util.logging.Logger.getLogger(AutoResponderClick.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
}
